<!--
Name: Simon X. Han
Project 1A
-->
<html>
<?php
  function span($text,$style) {
    return "<span style=\"$style\">$text</span></br>";
  }
?>
<body>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<span>Welcome to the calculator. Enter a mathematical expression and click calculate:</span></br>
<input type="text" size="12" name="calcstr">
<input type="submit" name="submit" value="calculate">
</br>
<?php
if ($_POST["calcstr"]) {
  $equ = $_POST["calcstr"];
  $ans = "Invalid Expression";
  echo span("You entered: " . $equ,"");

  // Strip all white spaces
  $equ = preg_replace("/\s+/", "", $equ);
  
  // 
  
  // We want the input to be valid: number [+-*/] number
  // Number can be negative and also decimal
  $pattern = "/^-?(\d+)?(\.\d+)?(([\+\-\*\/]){1}-?((\d+)?(\.\d+)?){1})*$/";
  if (preg_match($pattern,$equ,$matches)) {

	// Divided by 0 is invalid
	if (preg_match("/\d+\/0$/",$equ) || preg_match("/\d+\/0[\+\-\*\/]/",$equ)) {
	  echo span("Dividing by zero not allowed!","");
	} 
	// Invalid inputs: ++, **, //, ---, 1--, 1* etc
	elseif (preg_match("/([\+|\*|\/]{2})|(\-{3})/",$equ,$matches) || preg_match("/[\+\-\*\/]{1}$/",$equ,$matches)) {
	  echo span("Invalid input detected: " . $matches[0],"");
	}
	// So far so good? We might want to eval now
	else {
      // "1--1" is invalid. We must put a space between "--"
      $equ = preg_replace("/--/", "- -", $equ);
	  eval("\$ans = $equ;");
	}
  }

  echo span("Answer: " . $ans, "color: red");
}
// Say nothing was submitted if empty form
elseif (isset($_POST["submit"])) {
  echo span("Nothing was submitted!","");
}
?>

</body>
</html>
